<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Blog extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->helper('url','form');
        $this->load->model('articles');
        $this->load->library('pagination');
        $this->load->library('tweet');
    }
    
    private function check(){
        return (!$this->session->userdata('user'));
    }
    
    public function index(){
        $this->retrieve_article('web');
    }
    public function retrieve_article($categoryname){
        $idcategory=0;
        if($categoryname=='web'){
            $idcategory=1;
        }else if($categoryname=='mobile'){
            $idcategory=2;
        }else if($categoryname=='analyst'){
            $idcategory=3;
        }else if($categoryname=='event'){
            $idcategory=4;
        }else if($categoryname=='appreciation'){
            $idcategory=5;
        }else{
            show_404();
            return;
        }
        // pagination
        $config['base_url'] = base_url().'/blog/retrieve_article/'.$categoryname.'/';
        $config['total_rows'] = $this->articles->get_num_article($idcategory);
        $config['per_page'] = 4;
        $config['num_links'] = 5;
        $config['uri_segment'] = 4;
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['first_link'] = 'First';
        $config['first_tag_open'] = '<div>';
        $config['first_tag_close'] = '</div>';
        $config['last_link'] = 'Last';
        $config['last_tag_open'] = '<div>';
        $config['last_tag_close'] = '</div>';
        $config['use_page_numbers'] = TRUE;

        $this->pagination->initialize($config);
        
        $data['title'] = 'blog';
        $data['category'] = $categoryname;
        $data['articles'] = $this->articles->retrieve_article($idcategory,$config['per_page'],$this->uri->segment(4));
        //$data['articles'] = $this->articles->retrieve_article($idcategory,$config['per_page'],$config['uri_segment']);
        $data['content'] = $this->load->view('blog/blog',$data,TRUE);
        $this->load->view('front',$data);
    }
    public function search_article(){
        $param = $_POST['search'];
        // pagination
        $config['base_url'] = base_url().'/blog/search/' .$param .'/';
        $config['total_rows'] = $this->articles->get_num_searcharticle($param);
        $config['per_page'] = 4;
        $config['num_links'] = 5;
        $config['uri_segment'] = 4;
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['first_link'] = 'First';
        $config['first_tag_open'] = '<div>';
        $config['first_tag_close'] = '</div>';
        $config['last_link'] = 'Last';
        $config['last_tag_open'] = '<div>';
        $config['last_tag_close'] = '</div>';
        $config['use_page_numbers'] = TRUE;
        $this->pagination->initialize($config);
         
        $data['title'] = 'blog';
        $data['category'] = 'search';
        $data['articles'] = $this->articles->search_article($param,$config['per_page'],$this->uri->segment(4));
        $data['content'] = $this->load->view('blog/blog',$data,TRUE);
        $this->load->view('front',$data);
    }
    public function search($param){
        // pagination
        $config['base_url'] = base_url().'/blog/search/' .$param .'/';
        $config['total_rows'] = $this->articles->get_num_searcharticle($param);
        $config['per_page'] = 4;
        $config['num_links'] = 5;
        $config['uri_segment'] = 4;
        $config['full_tag_open'] = '<p>';
        $config['full_tag_close'] = '</p>';
        $config['first_link'] = 'First';
        $config['first_tag_open'] = '<div>';
        $config['first_tag_close'] = '</div>';
        $config['last_link'] = 'Last';
        $config['last_tag_open'] = '<div>';
        $config['last_tag_close'] = '</div>';
        $config['use_page_numbers'] = TRUE;
        $this->pagination->initialize($config);
         
        $data['title'] = 'blog';
        $data['category'] = 'search';
        $data['articles'] = $this->articles->search_article($param,$config['per_page'],$this->uri->segment(4));
        $data['content'] = $this->load->view('blog/blog',$data,TRUE);
        $this->load->view('front',$data);
    }
    public function retrieve_read_article($idarticle){
        $data['title'] = 'blog';
        $data['articles'] = $this->articles->retrieve_read_article($idarticle);
        $data['content'] = $this->load->view('blog/read_blog',$data,TRUE);
        $this->load->view('front',$data);
    }
    public function display_form($format=null,$idart=null){
        if($this->check()) {
            show_404();
            return;
        }
        $data['title'] = 'blog';
        $data['category'] = $this->articles->retrieve_category();
        if($format=="add"){
           $data['content'] = $this->load->view('blog/add_blog',$data,TRUE);
        }else if($format=="edit"){
           $data['article'] = $this->articles->retrieve_article_byidart($idart);
           $data['article_category'] = $this->articles->retrieve_category_byidart($idart);
           $data['content'] = $this->load->view('blog/edit_blog',$data,TRUE);
        }else if($format=="delete"){
           $url_image = $this->articles->getImage_byidart($idart);
           unlink('./assets/images/'.$url_image[0]->url_image);
           $this->articles-> delete_category_article($idart);
           $this->articles-> delete_article($idart);
           echo "Hapus Artikel Berhasil";
           $data['content'] = "";
        }
        $this->load->view('front',$data);
    }
    public function add_article(){
        if($this->check()) {
            show_404();
            return;
        }
        $this->load->helper('url','form');
        $data['title'] = 'contributor - add article';
        
        /*** GET FORM ***/
        // ambil semua post
        $article = array();
        $article['judul']=$_POST['judul'];
        $article['penulis']=$_POST['penulis'];
        $text = '';
        foreach(explode("\n", $_POST['konten']) as $row){
            $text = $text .$row .'<br/>';
        }
        $article['konten']=$text;
        $nowdate = getdate();
        $realdate = $nowdate['year'] ."-" .$nowdate['mon'] ."-" .$nowdate['mday'] ." " .$nowdate['hours'] .":" .$nowdate['minutes'] .":" .$nowdate['seconds'];
        $article['timestamp']=$realdate;
        
        //upload file
        $config['upload_path'] = './assets/images/articles/';
        $config['allowed_types'] = 'jpg|jpeg|png|bmp';
        $config['max_width'] = '1024';
        $config['max_height'] = '1024';
        $config['overwrite'] = 'TRUE';
        $this->load->library('upload', $config);
        /*** SEND FORM ***/
        if (!$this->upload->do_upload() || $article['judul']==null || 
                $article['penulis']==null || $article['konten'] == null
                )
        {
            // kalo gagal
            $error = array('error' => $this->upload->display_errors());
            print_r($error);
            echo ", Form Not Valid";
            //redirect('blog/display_form');
        }    
        else
        {
            // kalo berhasil
            $data = array('upload_data' => $this->upload->data());
            $fileName = $data['upload_data']['orig_name'];
            $tmpName  = $data['upload_data']['full_path'];
            $fileSize = $data['upload_data']['file_size'];
            $fileType = $data['upload_data']['file_type'];    
            foreach( $data as $item => $value ) { 
                $filedata[$item] = $value; 
            }
            $article['url_image'] = 'articles/'.$fileName;
            
            /**** INSERT TO DATABASE ****/
            // insert into tabel artikel
            $this->articles->add_article($article);
            
            
            // insert into tabel kategori_artikel
            // ambil kategori yang terdaftar
            $category = $this->articles->retrieve_category();
            // ambil index artikel terakhir
            $lastindexarticle = $this->articles->GLI_article();
            // looping kategori yang ON
            if($category!=false){
                foreach($category as $rows){ 
                    //echo $_POST[$rows->nama];
                    //echo "<br/>";
                    if(isset($_POST[$rows->nama]))
                    {
                        $indexcategory = $this->articles->GI_article_byname($rows->nama);
                        $catart['idkategori'] = $indexcategory[0]->idkategori;
                        $catart['idartikel'] = $lastindexarticle[0]->idartikel;
                        $this->articles->add_category_article($catart);
                    }
                }
            }
            
            // posting to @inkubatorIT twitter
            if ( !$this->tweet->logged_in() )
            {
                    // This is where the url will go to after auth.
                    // ( Callback url )
                    $this->tweet->set_callback(site_url('tweet_test/auth'));
                    // Send the user off for login!
                    $this->tweet->login();
            }
            else
            {
                    // shorten url
                    $url = urlencode(base_url().'retrieve_read_article/'.$catart['idartikel']);
                    # Send request, $x will contain the response from our API.
                    # We do a trim() also to get rid of the new line character at the end of the string.
                    $x = trim( file_get_contents('http://clicky.me/app/api?username=maulnick&password=fidriany&site_id=66536996&url='.$url));

                    # If the returned string starts with http://, the request was successful.
                    if( preg_match( '#^http://#', $x )) {
                      # Success! Do something with $x, which contains the shortened URL.
                        //print_r($x);
                    }
                    else {
                      # Failure! $x will contain the error.
                      # You can output it to the user or do whatever you want with it.
                        //print_r($x);
                    }
                    // posting
                    $this->tweet->call('post', 'statuses/update', array('status' => '[News] ' .$article['judul'] .'. Check this out ' .$x));
            }
            // kalo berhasil
            echo "Artikel telah ditambah dan diposting ke twitter @inkubatorIT";
            $this->index();
        }
    }

    public function edit_article($idarticle){
        if($this->check()) {
            show_404();
            return;
        }
        $this->load->helper('url','form');
        $data['title'] = 'contributor - edit article';
        
        /*** GET FORM ***/
        // ambil semua post
        $article = array();
        $pictfile = $_POST['pictfile'];
        $article['judul']=$_POST['judul'];
        $article['penulis']=$_POST['penulis'];
        
        $text = '';
        foreach(explode("\n", $_POST['konten']) as $row){
            $text = $text .$row .'<br/>';
        }
        $article['konten']=$text;
        
            $nowdate = getdate();
            print_r($nowdate);
            $realdate = $nowdate['year'] ."-" .$nowdate['mon'] ."-" .$nowdate['mday'] ." " .$nowdate['hours'] .":" .$nowdate['minutes'] .":" .$nowdate['seconds'];
            //echo ($realdate);
            $article['timestamp']=$realdate;
        if($article['judul']==null || $article['penulis']==null || $article['konten'] == null){
            echo ", Form Not Valid";
        }else{
            // form tidak kosong
            if (($_FILES['userfile']['name'])=="")
            {
               // kalo user ga upload file picture yang baru dan berarti udah ada
                echo "Tidak ada perubahan image";echo "</br>";
   	       $article['url_image'] = $pictfile;
               $this->articles->update_article($idarticle, $article);
               
               
               // delete kategori yang lama
               $this->articles->delete_category_article($idarticle);
               
               // insert kategori yang baru
               // ambil kategori yang terdaftar
                $category = $this->articles->retrieve_category();
                // looping kategori yang ON
                if($category!=false){
                    foreach($category as $rows){ 
                        //echo $_POST[$rows->nama];
                        //echo "<br/>";
                        if(isset($_POST[$rows->nama]))
                        {
                            $indexcategory = $this->articles->GI_article_byname($rows->nama);
                            $catart['idkategori'] = $indexcategory[0]->idkategori;
                            $catart['idartikel'] = $idarticle;
                            $this->articles->add_category_article($catart);
                        }
                    }
                }
                echo "Edit Artikel berhasil";
	    }else{
                // kalo user upload file baru
                //upload file
                $config['upload_path'] = './assets/images/articles/';
                $config['allowed_types'] = 'jpg|jpeg|png|bmp';
                $config['max_width'] = '1024';
                $config['max_height'] = '1024';
                $config['overwrite'] = 'TRUE';
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload() )
                {
                    // kalo gagal upload
                    $error = array('error' => $this->upload->display_errors());
                    print_r($error);
                    echo ", Error uploading file - Form Not Valid";
                    //redirect('blog/display_form');
                }    
                else
                {
                    // kalo user berhasil upload
                    // delete file yang lama dulu
                    echo "Ada perubahan image";echo "</br>";
                    unlink('./assets/images/'.$pictfile);
                    $data = array('upload_data' => $this->upload->data());
                    $fileName = $data['upload_data']['orig_name'];
                    $tmpName  = $data['upload_data']['full_path'];
                    $fileSize = $data['upload_data']['file_size'];
                    $fileType = $data['upload_data']['file_type'];    
                    foreach( $data as $item => $value ) { 
                        $filedata[$item] = $value; 
                    }
                    $article['url_image'] = 'articles/'.$fileName;

                    /**** INSERT TO DATABASE ****/
                    // edit tabel artikel
                    $this->articles->update_article($idarticle, $article);
                    
                    // delete kategori yang lama
                    $this->articles->delete_category_article($idarticle);
                   // insert kategori yang baru
                   // ambil kategori yang terdaftar
                    $category = $this->articles->retrieve_category();
                    // looping kategori yang ON
                    if($category!=false){
                        foreach($category as $rows){ 
                            //echo $_POST[$rows->nama];
                            //echo "<br/>";
                            if(isset($_POST[$rows->nama]))
                            {
                                $indexcategory = $this->articles->GI_article_byname($rows->nama);
                                $catart['idkategori'] = $indexcategory[0]->idkategori;
                                $catart['idartikel'] = $idarticle;
                                $this->articles->add_category_article($catart);
                            }
                        }
                    }
                    echo "Edit Artikel berhasil";
                    $this->index();
                }
            }
        }
        
        
    }
}